#include "common.h"




unsigned short ModBusCRC16(unsigned char *buf, int len) {
    if ((!buf) || (len < 1)) return 0xFFFF;
    unsigned short CRC16 = 0xFFFF;
    for (int n = 0; n < len; n++) {
        CRC16 ^= buf[n];
        for (int i = 0; i < 8; i++) {
            if (CRC16 & 0x01) {
                CRC16 = CRC16 >> 1;
                CRC16 ^= 0xa001;
            } else {
                CRC16 = CRC16 >> 1;
            }
        }
    }
    return CRC16;
}

unsigned char getIndex(void) {
//    return 1;
    static unsigned char _index = 1;
    if (_index >= 255) _index = 1;

    return _index++;
}

//void empty_Lqueue(osMessageQId handle) {
//    osEvent ret = osMessageGet(handle, 0);
//    while (osEventMessage == ret.status) {
//        vPortFree(ret.value.p);
//        ret = osMessageGet(handle, 0);
//    }
//}

/*
 * checkcrc is correct
 * data len
* return:true:crc correct,false:crc incorrect
 */
bool checkCRC(unsigned char *data, int len) {
    unsigned short ret = ModBusCRC16(data, len - 2);
    return ((data[len - 2] | (data[len - 1] << 8)) == ret) ? true : false;
}

bool abs_duration_timeout(unsigned int start,unsigned int end,unsigned int duration){

    return start>end?\
        (start-end)>duration?true:false:\
            (end-start)>duration?true:false;
}


int getAverage(unsigned short buf[],int len){
    int sum=0;
    for(int i=0;i<len;i++){
        sum+=buf[i];
    }
    return sum/len;
}
